Sorting
sorting in python is very readable. Here are some fun sorting algorithms to read:
Bogo Sort
- This sorting algorithm simply shuffles the set until it is sorted. This is one of the most notoriously inefficient sorting algorithms there is.
def bogo_sort(collection):
def is_sorted(collection):
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True
while not is_sorted(collection):
random.shuffle(collection)
return collection
Bubble Sort
- bubble sort is a very beginner friendly sorting algorithm. It's probably one of the easiest to understand. You iterate through the list at worse
n*ntimes and for each iteration, you swap the current element if it is greater than the next element. The effect of this is that larger values bubble to the end of the list.
def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
length = len(collection)
for i in reversed(range(length)):
swapped = False
for j in range(i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection